package com.example.demo.util;

import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.ThreadLocalRandom;

/**
 * @author gxing
 * @desc 随机字符串
 * @date 2022/11/1
 */
public class RandomStrUtil {
    private static final String ALPHABET = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
    private static final int ALPHABET_LENGTH = ALPHABET.length();

    /**
     * @desc 默认生成8位长度的随字符串
     * @author gxing
     * @date 2022/11/1 16:22
     */
    public static String generate() {
        return generate(8);
    }

    /**
     * @param length 长度
     * @desc 生成指定长度的随字符串
     * @author gxing
     * @date 2022/11/1 16:22
     */
    public static String generate(int length) {
        StringBuilder sb = new StringBuilder();
        ThreadLocalRandom current = ThreadLocalRandom.current();
        for (int i = 0; i < length; i++) {
            int i1 = current.nextInt(ALPHABET_LENGTH);
            char c = ALPHABET.charAt(i1);
            sb.append(c);
        }
        return sb.toString();
    }

    /**
     * @param length 长度
     * @param size 个数
     * @desc 生成指定长度的随字符串
     * @author gxing
     * @date 2022/11/1 16:22
     */
    public static Set<String> generateList(int length, int size) {
        StringBuilder sb = new StringBuilder();
        ThreadLocalRandom current = ThreadLocalRandom.current();
        Set<String> randomSet = new HashSet<>();
        while (randomSet.size() < size) {
            for (int j = 0; j < length; j++) {
                int i1 = current.nextInt(ALPHABET_LENGTH);
                char c = ALPHABET.charAt(i1);
                sb.append(c);
                randomSet.add(sb.toString());
            }
        }
        return randomSet;
    }

}
